<template>
    <div class="shop-cart">
        <Shortcut></Shortcut>
        <Header></Header>
        <div class="goods">
            <div class="goods-num">
                全部商品&nbsp;&nbsp;{{ cartSumNums }}
            </div> 
            <table>
                <thead>
                    <th><input type="checkbox" :checked="allChecked" @click="checkedAll">全选</th>
                    <th>商品</th>
                    <th></th>
                    <th>单价</th>
                    <th>数量</th>
                    <th>小计</th>
                    <th>操作</th>
                </thead>
                <tbody>
                    <!-- 这里写循环 -->
                    <tr v-for="(item,index) in cartListData" :key="index">
                        <td><input type="checkbox" :checked="item.checked" @click="changeChecked(item.sku_id)"></td>
                        <td><img :src="item.goods.image" alt=""></td>
                        <td>{{ item.goods.name }}</td>
                        <td>&yen;{{ item.goods.p_price }}</td>
                        <td><el-input-number v-model="item.nums" :min="1" :max="100" @change="(newValue,oldValue) => handleChange(newValue,oldValue,item.sku_id)"></el-input-number></td>
                        <td>&yen;{{ (item.nums * item.goods.p_price).toFixed(2) }}</td>
                        <td>删除</td>
                    </tr>
                </tbody>
            </table>
            <div class="bottom-tool">
                <div class="tool-left">
                    <input type="checkbox" :checked="allChecked" @click="checkedAll">
                    全选
                    <span class="delete-selected" @click="deleteGoods(0)">删除选中商品</span>
                    <span class="clear-cart" @click="deleteGoods(1)">清除购物车</span>
                </div>
                <div class="tool-right">
                    <span class="selected-goods">已选择<em>{{ selectedGoodsCount }}</em>件商品</span>
                    <span class="price-count">总价：<em>&yen;{{ priceCount.toFixed(2) }}</em></span>
                    <a href="#" class="go-order" @click="goOrder">去结算</a>
                </div>
            </div>
            
        </div>
    </div>
</template>

<script setup>
    import Shortcut from '@/components/common/Shortcut.vue'
    import Header from '@/components/home/Header.vue'
    import { getCartDetailData,updateCartGoodsNumData } from '@/network/cart'
    import store from '@/store';
    import { deleteCartGoods } from '@/network/cart'
    import { onMounted,ref,watch } from 'vue'
    import router from '@/router';
    import { createOrderData } from '@/network/order'

    let cartListData = ref([])
    let cartSumNums = ref(0)

    const getCartDetail = async () => {
        const result = await getCartDetailData()
        cartListData.value = result
        //计算商品总数
        cartSumNums.value = cartListData.value.reduce((pre,current) => {
            return pre + current.nums
        },0)
    }

    onMounted(() => {
        //这里后续我们要进行代码的健壮性书写
        //这里要验证用户的登录状态
        getCartDetail()
        store.dispatch("updateCart")

    })

    //修改购物车中商品的数量
    const handleChange = (newValue,oldValue,skuId) => {
        console.log(newValue,oldValue,skuId)
        let data = ref({
            sku_id:skuId,
            nums:newValue
        })
        //更新商品数量
        updateCartGoodsNumData(data.value).then((res) => {
            // console.log(res)
            store.dispatch('updateCart')
            //这种实现方式有bug，因为updateCart里面调用了异步函数，所以updateCart是异步的,还没等updateCart执行完毕将
            //store.state.CartCount赋新的值，就执行了下面的cartSumNums.value = store.state.CartCount，从而获取到的是没有更新的值
            // cartSumNums.value = store.state.CartCount
        })
        cartSumNums.value += newValue - oldValue
    }


    //全选与取消全选的逻辑
    let allChecked = ref(false)
    const checkedAll = () => {
        if(allChecked.value === false) {
            //点击了全选
            cartListData.value.forEach(item => item.checked = true)
            allChecked.value = true
            //更新商品的件数
            selectedGoodsCount.value = cartListData.value.reduce((pre,current) => {
                return pre + current.nums
            },0)
            
        }else {
            //取消了全选
            cartListData.value.forEach(item => item.checked = false)
            allChecked.value = false
            //更新商品的件数
            selectedGoodsCount.value = 0
        }
    }

    //计算商品的总件数与总价格
    let selectedGoodsCount = ref(0)
    let priceCount = ref(0)

    //计算商品总价
    watch(cartListData,(newValue,oldValue) => {
            priceCount.value = 0
            cartSumNums.value = 0
            cartListData.value.forEach((item) => {
                if(item.checked) {
                    priceCount.value += item.goods.p_price * item.nums
                }
                cartSumNums.value += item.nums
            })
            
    },{
        //加一个深度监听参数，才能监听到ref变量中包含列表，列表中包含json的值的变化
        deep:true
    })



    //单个选中与取消商品的逻辑
    const changeChecked = (id) => {
        cartListData.value.forEach(item => {
            if(item.sku_id === id) {
                item.checked = !item.checked
            }
        })
        //修改选中商品的数量
        selectedGoodsCount.value = 0
        cartListData.value.forEach(item => {
            if(item.checked) {
                selectedGoodsCount.value += item.nums
            }
        })
        //更新全选框的状态
        const all = cartListData.value.every(item => item.checked)
        if(all) {
            allChecked.value = true
        }else {
            allChecked.value = false
        }
    }

    //记录要删除的商品
    let deleteGoodsList = ref([])

    let noDeleteGoodsList = ref([])

    const deleteGoods = (deleteStatus) => {
        deleteGoodsList.value = []
        if(deleteStatus === 0) {
        cartListData.value.forEach((item) => {
            if(item.checked) {
                deleteGoodsList.value.push(item.sku_id)
            }else {
                noDeleteGoodsList.value.push(item)
            }
        })


        if(deleteGoodsList.value.length === 0) {
            alert("请先选择商品")
        }else {
        // 弹出确认框
        let res = confirm('此操作将会把商品永久的移除购物车,是否继续?')
        if(res) {
            //请求后端删除接口
            deleteCartGoods(deleteGoodsList.value).then(res => {
            alert("删除成功")

            //第一种方法可以手动刷新页面
            //location.reload()
            
            //第二种实现方式（最好）
            getCartDetail()
            store.dispatch('updateCart')
                

            selectedGoodsCount.value = 0

            //第三种方式
            //cartListData.value = noDeleteGoodsList.value
                
            })
        }else {
            alert("取消删除")
            // deleteGoodsList.value = []
        }
        }
    }else {
        let res = confirm("您将要清空购物车,是否继续?")
        if(res) {
            cartListData.value.forEach((item) => {
                deleteGoodsList.value.push(item.sku_id)
            })
            deleteCartGoods(deleteGoodsList.value).then((res) => {
                alert("清空购物车成功")
                getCartDetail()
                store.dispatch('updateCart')
                selectedGoodsCount.value = 0
                
                //window对象的跳转路由的方法
                location.href = '/'
            })
        }
    }
    }

    //去结算，创建订单功能实现
    let OrderGoodsList = ref([])
    const goOrder = () => {
        cartListData.value.forEach((item) => {
            if(item.checked) {
                OrderGoodsList.value.push(item)
            }
        })
        let OrderData = ref({
            trade:{
                order_amount:priceCount.value
            },
            goods:OrderGoodsList.value
        })
        //往后端发送网络请求
        let orderNo = ref('')
        createOrderData(OrderData.value).then(res => {
            orderNo.value = res.trade_no
            router.push('/order/' + orderNo.value)
            store.dispatch('updateCart')
        })

    }
</script>

<style lang="less" scoped>
    .shop-cart {
        .goods {
            width: var(--content-width);
            margin: 0 auto;
            .goods-num {
                color: #e2231a;
                font-size: 16px;
                font-weight: 700;
            }
            table {

                tr {
                    border-bottom: 1px solid #f0f0f0;
                }

                border-collapse: collapse;  //去掉单元格之间边界的白色间隔
                th {
                    background-color: #f3f3f3;
                    height: 45px;
                    &:nth-child(1) {
                        width: 50px;
                        padding-left: 10px;
                    }
                }
                td {
                    padding: 10px 0 10px;
                    img {
                        width: 45px;
                        height: 45px;
                        border: 1px solid #eeeeee;
                    }
                    &:nth-child(1) {
                        text-align: center;
                    }
                    &:nth-child(3) {
                        width: 700px;
                        padding-left: 10px;
                        padding-right: 30px;
                        &:hover {
                            color: #e2231a;
                            cursor: pointer;
                        }
                    }
                    &:nth-child(4) {
                        width: 80px;
                        text-align: center;
                    }
                    &:nth-child(5) {
                        width: 80px;
                        text-align: center;
                    }
                    &:nth-child(6) {
                        width: 120px;
                        text-align: center;
                        font-weight: 700;
                    }
                    &:nth-child(7) {
                        width: 80px;
                        text-align: center;
                    }
                }
            }
            .bottom-tool {
                margin-top: 10px;
                border: 1px solid #f0f0f0;
                height: 50px;
                line-height: 50px;
                display: flex;
                justify-content: space-between;
                .tool-left {
                    padding-left: 10px;
                    span {
                        padding: 0 10px;
                        &:hover {
                            color: #e2231a;
                            cursor: pointer;
                        }

                        &.clear-cart {
                            font-size: 14px;
                            font-weight: 700;
                        }
                    }
                }
                .tool-right {
                    span {
                        font-weight: 700;
                        color: #acacac;
                        em {
                            color: #e2231a;
                            font-weight: 700;
                            padding: 0 5px;
                        }
                        &.price-count {
                            em {
                                font-size: 16px;
                            }
                        }
                    }
                    .go-order {
                        // margin-right: 25px;
                        display: inline-block;
                        width: 95px;
                        height: 50px;
                        background-color: #e2231a;
                        color: white;
                        line-height: 50px;
                        text-align: center;
                        font-size: 18px;
                        font-weight: 700;
                    }
                }
            }
        }
    }
</style>